<template>
  <div class="bullet-package-ranking">
    <!-- 顶部标题 -->
    <div class="header">
      <n-space align="center" :size="10">
        <n-icon :size="26" color="#e6a23c">
          <BulletIcon />
        </n-icon>
        <n-text strong style="font-size: 20px;">子弹卡包</n-text>
      </n-space>
    </div>

    <!-- 卡包区域 -->
    <div class="package-cards-container">
      <!-- 动态渲染所有卡包 -->
      <div
        v-for="config in packageConfigs"
        :key="config.id"
        class="package-card"
        :class="{ 'pass-package': config.isPassPackage }"
      >
        <div class="package-card-header">
          <div class="package-title">
            <div
              class="grade-indicator"
              :class="`grade-${config.grade}`"
            >
              {{ config.grade }}级
            </div>
            <span class="package-name">{{ config.name }}</span>
            <span v-if="config.isPassPackage" class="pass-badge">通行证</span>
          </div>
          <div class="package-description">{{ config.description }}</div>
          <div class="package-count">共 {{ packageData[config.id]?.total || 0 }} 种弹药</div>
        </div>
        <div class="package-card-content">
          <BulletList
            :items="packageData[config.id]?.list || []"
            :loading="loading"
            :total="packageData[config.id]?.total || 0"
            :page="pageStates[config.id]?.page || 1"
            :page-size="pageSize"
            @page-change="(p) => onPackagePageChange(config.id, p)"
            @page-size-change="(s) => onPackagePageSizeChange(config.id, s)"
            @item-click="showItemDetail"
          />
        </div>
      </div>
    </div>

    <!-- 物品详情弹窗 -->
    <ItemDetailModal
      v-model:show="showDetailModal"
      :object-id="selectedItemId"
    />
  </div>
</template>

<script setup lang="ts">
// --------------- 依赖导入 ---------------
import { ref, onMounted, h } from 'vue'
import { NSpace, NText } from 'naive-ui'
import { getBulletPackageRanking } from '@/api/ranking'
import type { BulletPackageRankingItem } from '@/types/ranking'
import ItemDetailModal from '../../../components/ItemDetailModal.vue'
import BulletList from '../components/BulletList.vue'

// 子弹图标组件
const BulletIcon = () => h('svg', {
  viewBox: '0 0 24 24',
  fill: 'currentColor'
}, [
  h('path', {
    d: 'M12 2C13.1 2 14 2.9 14 4V8H16C17.1 8 18 8.9 18 10V20C18 21.1 17.1 22 16 22H8C6.9 22 6 21.1 6 20V10C6 8.9 6.9 8 8 8H10V4C10 2.9 10.9 2 12 2Z'
  })
])

// --------------- 类型定义 ---------------
interface PackageData {
  list: BulletPackageRankingItem[]
  total: number
}

interface PageState {
  page: number
}

interface PackageConfig {
  id: string
  name: string
  description: string
  grade: number
  isPassPackage?: boolean
}

// --------------- 响应式状态 ---------------
const loading = ref(false)
const pageSize = ref(5) // 每个卡包列表的分页大小

// 卡包配置
const packageConfigs = ref<PackageConfig[]>([
  { id: 'grade_3', name: '3级弹药卡包', description: '包含各种3级弹药，适合日常使用', grade: 3 },
  { id: 'grade_4', name: '4级弹药卡包', description: '包含各种4级弹药，性能更优', grade: 4 },
  { id: 'grade_5', name: '5级弹药卡包', description: '包含各种5级弹药，顶级性能', grade: 5 },
  { id: 'pass_basic', name: '通行证基础子弹自选包', description: '通行证专属，包含精选3级弹药', grade: 3, isPassPackage: true },
  { id: 'pass_advanced', name: '通行证高级子弹自选包', description: '通行证专属，包含精选4级弹药', grade: 4, isPassPackage: true }
])

// 卡包数据
const packageData = ref<Record<string, PackageData>>({})

// 各卡包的分页状态
const pageStates = ref<Record<string, PageState>>({})

// 详情弹窗相关状态
const showDetailModal = ref(false)
const selectedItemId = ref<number | null>(null)

// --------------- 方法 ---------------
// 初始化分页状态
const initializePageStates = () => {
  packageConfigs.value.forEach(config => {
    pageStates.value[config.id] = { page: 1 }
  })
}

// 获取所有卡包数据
const fetchInitialData = async () => {
  try {
    loading.value = true

    // 获取所有卡包的数据
    const resp = await getBulletPackageRanking({ grade: 0 })

    if (resp.code === 1 && resp.data) {
      // 直接使用后端返回的数据，确保 total 与 list.length 一致
      const data = resp.data as any
      packageData.value = {}

      Object.keys(data).forEach(packageId => {
        const packageInfo = data[packageId] || { list: [], total: 0 }
        packageData.value[packageId] = {
          list: packageInfo.list || [],
          total: packageInfo.list ? packageInfo.list.length : 0
        }


      })
    }
  } catch (err) {
    console.error('获取子弹卡包数据失败', err)
  } finally {
    loading.value = false
  }
}

// 卡包分页变化
const onPackagePageChange = (packageId: string, page: number) => {
  if (pageStates.value[packageId]) {
    pageStates.value[packageId].page = page
  }
}

// 卡包分页大小变化
const onPackagePageSizeChange = (packageId: string, size: number) => {
  pageSize.value = size

  // 分页大小变化时，重置到第一页
  if (pageStates.value[packageId]) {
    pageStates.value[packageId].page = 1
  }
}

// 显示物品详情
const showItemDetail = (objectId: number) => {
  console.log('BulletPackageRanking: 点击显示物品详情, objectId:', objectId)
  selectedItemId.value = objectId
  showDetailModal.value = true
}

// 组件挂载时加载数据
onMounted(() => {
  initializePageStates()
  fetchInitialData()
})
</script>

<style scoped>
.bullet-package-ranking {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.header {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.package-cards-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 16px;
  align-items: stretch; /* 确保所有卡片高度一致 */
}

.package-card {
  background: var(--n-card-color);
  border: 1px solid var(--n-border-color);
  border-radius: 8px;
  overflow: hidden;
  min-width: 0; /* 允许内容收缩 */
  display: flex;
  flex-direction: column;
  transition: all 0.3s ease;
}

.package-card.pass-package {
  border: 2px solid var(--n-primary-color);
  box-shadow: 0 4px 12px rgba(24, 160, 88, 0.15);
}

.package-card-header {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 12px 16px;
  background: var(--n-modal-color);
  border-bottom: 1px solid var(--n-border-color);
  flex-shrink: 0;
}

.package-title {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 0;
}

.grade-indicator {
  padding: 3px 6px;
  border-radius: 4px;
  font-size: 11px;
  font-weight: bold;
  color: white;
  min-width: 32px;
  text-align: center;
  flex-shrink: 0;
}

.grade-3 {
  background: var(--grade-border-3);
}

.grade-4 {
  background: var(--grade-border-4);
}

.grade-5 {
  background: var(--grade-border-5);
}

.package-name {
  font-size: 14px;
  font-weight: 600;
  color: var(--n-text-color-1);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.pass-badge {
  background: var(--n-primary-color);
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 10px;
  font-weight: bold;
  margin-left: auto;
}

.package-description {
  font-size: 12px;
  color: var(--n-text-color-2);
  line-height: 1.4;
}

.package-count {
  font-size: 12px;
  color: var(--n-text-color-3);
  white-space: nowrap;
  flex-shrink: 0;
}

.package-card-content {
  padding: 0;
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  min-height: 0; /* 允许内容收缩 */
}

/* 响应式设计 */
@media (max-width: 1400px) {
  .package-cards-container {
    gap: 12px;
  }
}

@media (max-width: 1200px) {
  .package-cards-container {
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
  }
}

@media (max-width: 900px) {
  .package-cards-container {
    grid-template-columns: 1fr;
    gap: 16px;
  }
}

@media (max-width: 768px) {
  .bullet-package-ranking {
    gap: 12px;
  }

  .package-card-header {
    padding: 10px 12px;
  }

  .package-title {
    gap: 6px;
    width: 100%;
  }

  .package-name {
    font-size: 13px;
  }

  .package-count {
    font-size: 11px;
  }

  .grade-indicator {
    font-size: 10px;
    padding: 2px 5px;
    min-width: 28px;
  }
}
</style>
